package com.dgut.coal.controller;

import com.dgut.coal.entity.Info;
import com.dgut.coal.entity.User;
import com.dgut.coal.service.InfoService;
import com.dgut.coal.service.UserService;
import com.dgut.coal.util.PasswordMD5Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @Author: Yang
 * @Description:
 * @Date: Created in 16:12 2019/9/28
 * @Modifued BY:
 */

@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    InfoService is;

    /**
    ** 判断登录用户
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String username, String password, String code, HttpSession session, HttpServletRequest request){

        String password_md5 = PasswordMD5Utils.getMD5String(password);
        User user = userService.findUser(username,password_md5);

        String random = request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY).toString().toLowerCase();
        if (user != null && random.equals(code.toLowerCase())){

            int role_type = user.getRole_type();
            session.setAttribute("user",user);
//            session.setAttribute("errormsg","");
            return "admin-index";
        }else if(user == null){
            session.setAttribute("errormsg","用户名或密码错误");
            return "redirect:main";

        }else {
            session.setAttribute("errormsg","验证码错误");
            return "redirect:main";
        }

//        return "redirect:main";
    }


    /**
    ** 进入前台首页
     */
    @RequestMapping("/main")
    public String main(Map<String, Object> map){
        List<Info> lastest = is.lastest();
        //List<Info> list = is.infolist(null,null,null);
        map.put("lastest",lastest);
        //map.put("list",list);
        return "main";

    }

    /**
    ** 退出登录
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){

        session.invalidate();
        return "redirect:main";
    }

}
